﻿using Creator.Core.Component;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Creator.Core
{
    public static class Entrey
    {
        public static bool isRunning { get; private set; }
        /// <summary>
        /// 每次运行的增量时间
        /// </summary>
        public static double deltaTime { get; private set; }
        /// <summary> 
        /// 从开始运行的实际时间
        /// </summary>
        public static double realTime { get; private set; }
        
        public static void Run()
        {
            var processes = SystemData.ProcessObjects;
            isRunning = true;


            //逻辑初始化 
            var logcis = SystemData.ProcessObjects.SelectMany(a => a.Behaviours).OfType<LogicComponet>();
            foreach (var logic in logcis)
            {
                logic.Init();
            } 
            //界面渲染初始化
            var renders = SystemData.ProcessObjects.SelectMany(a => a.Behaviours).OfType<RenderComponent>();
            foreach (var render in renders)
            {
                render.Init();
            }
             
            Stopwatch stopwatch = new Stopwatch(); 
            stopwatch.Start();

            // 记录上一帧的时间
            double lastFrameTime = 0;
            while (isRunning)
            {
                double currentTime = realTime = stopwatch.Elapsed.TotalSeconds;

                // 计算 deltaTime
                deltaTime = currentTime - lastFrameTime;
                foreach (var action in processes)
                {
                    if (action.Behaviours == null || action.Behaviours.Count == 0) continue;
                    foreach (var behaviour in action.Behaviours)
                    {
                        if (!behaviour.Active) continue;
                        behaviour.Run(deltaTime);
                    }
                }
                // 记录上一帧的时间
                lastFrameTime = currentTime;

                //每秒 1帧
                Thread.Sleep(1000 / 1); 
            }
            //停止
            foreach (var action in processes)
            {
                foreach (var behaviour in action.Behaviours)
                {
                    behaviour.Stop();
                }
            }
        }

        public static void Stop()
        {
            isRunning = false;
        }
    }
}
